package com.heima.search.service.impl;

import com.heima.common.exception.CustException;
import com.heima.es.service.EsService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.UserSearchDTO;
import com.heima.model.search.vos.SearchArticleVO;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.service.ApUserSearchService;
import com.heima.search.service.ArticleSearchService;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class ArticleSearchServiceImpl implements ArticleSearchService {
    public static final String APP_INFO_ARTICLE = "app_info_article";
    @Value("${file.minio.readPath}")
    String readPath;

    @Autowired
    EsService<SearchArticleVO> esService;


    @Autowired
    ApUserSearchService apUserSearchService;

    @Override
    public ResponseResult search(UserSearchDTO dto) {
        // 检查参数
        String words = dto.getSearchWords();
        if (StringUtils.isBlank(words)) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在");
        }

        ApUser user = AppThreadLocalUtils.getUser();
        if (user != null) dto.setEntryId(user.getId());
        // 异步调用保存用户输入关键词记录
        apUserSearchService.insert(dto);

        if (dto.getMinBehotTime() == null) {
            dto.setMinBehotTime(new Date());
        }

        // 构建查询参数 searchSourceBuilder
        SearchSourceBuilder builder = new SearchSourceBuilder();
        // 构建bool条件
        BoolQueryBuilder queryBool = QueryBuilders.boolQuery();
        //  使用match 查询title==>must
        queryBool.must(QueryBuilders.matchQuery("title", words));
        //  使用range 查询publish<minDate==>filter
        queryBool.filter(QueryBuilders.rangeQuery("publishTime").lt(dto.getMinBehotTime()));
        builder.query(queryBool);
        // 排序条件 按照发布时间降序排序

        // 设置高亮条件 高亮字段:title <span></span>
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("title");
        highlightBuilder.preTags("<font style='color: red; font-size: inherit;'>");
        highlightBuilder.postTags("</font>");
        builder.highlighter(highlightBuilder);
        // 扉页条件 size: 每页条数
        builder.sort("publishTime", SortOrder.DESC);
        builder.size(dto.getPageSize());

        // 调用search方法 执行搜索
        PageResponseResult result = esService.search(builder, SearchArticleVO.class, APP_INFO_ARTICLE);
        // 在结果添加 静态页面的访问前缀
        List<SearchArticleVO> list = (List<SearchArticleVO>) result.getData();
        for (SearchArticleVO searchArticleVO : list) {
            searchArticleVO.setStaticUrl(readPath + searchArticleVO.getStaticUrl());
        }
        return result;
    }

    /**
    保存 es
     */
    @Override
    public void saveArticle(SearchArticleVO article) {
        esService.save(article, APP_INFO_ARTICLE);
    }

    @Override
    public void deleteArticle(String articleId) {
        esService.deleteById(articleId,APP_INFO_ARTICLE);
    }
}

